package com.sz.controller;

import com.sz.model.Result;
import com.sz.myinterface.SMSCode;
import com.sz.service.IEditService;
import com.sz.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edit")
public class EditController {

    @Autowired
    private IEditService iEditService;

    @Autowired
    private Md5Util md5Util;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/password") // 修改密码，前端传输用户名，新密码和验证码
    public Result ChangePassword(String username, String password, String checkCode) {
        System.out.println(username+"--------------");
        String code=redisTemplate.opsForValue().get("checkCode");

        if (code!=null&&code.equals(checkCode)) {
            String md5 = md5Util.getSaltMD5(password);
            iEditService.ChangePassword(username, md5);
            return new Result(200,"修改成功");
        }else{
            return new Result(301,"修改失败");
        }

    }

    @RequestMapping("/sendNew") // 发送短信验证，并将验证码存到redis
    public String sendNews(String mobile) {
        String sc = SMSCode.sendSMS(mobile);
        redisTemplate.opsForValue().set("checkCode", sc,1, TimeUnit.MINUTES);

        System.out.println("sc = " + sc);
        return sc;
    }

    @RequestMapping("/out") // 退出登录，将redis中的token删除
    public String out(String username) {
        redisTemplate.delete(username);
        return "success";
    }
}
